<template>
	<view class="chat-container">
		<!-- 头部导航 - 修改为左对齐样式 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="left" @tap="goBack">
				<text class="back-icon">〈</text>
			</view>
			<view class="title-container">
				<view class="avatar-title">
					<image class="avatar" :src="deviceInfo?.icon" mode="aspectFill" />
					<view class="title-info">
						<text class="name">{{ deviceInfo?.name }}</text>
						<text class="creator">@{{ deviceInfo?.creatorName }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 消息列表 -->
		<scroll-view class="message-list" scroll-y :scroll-into-view="lastMessageId" :scroll-with-animation="true"
			@scrolltoupper="loadMoreHistory">
			<block v-if="messages.length">
				<template v-for="(msg, index) in messages" :key="msg.id">
					<!-- 时间戳 -->
					<view v-if="shouldShowTimestamp(msg, messages[index - 1])" class="time-stamp">
						{{ formatTime(msg.timestamp) }}
					</view>

					<!-- 消息气泡 -->
					<view :id="`msg-${msg.id}`" :class="['message-item', msg.role]">
						<image class="avatar" :src="msg.role === 'assistant' ? deviceInfo?.icon : userInfo?.avatar"
							mode="aspectFill" />
						<view class="content">{{ msg.content }}</view>
					</view>
				</template>
			</block>
		</scroll-view>

		<!-- 底部输入区 -->
		<view class="input-box">
			<input v-model="inputContent" class="input" type="text" placeholder="发送消息..." confirm-type="send"
				@confirm="sendMessage" />
			<button class="send-btn" :class="{ active: inputContent }" @tap="sendMessage">
				发送
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		nextTick,
		watch
	} from 'vue' // 添加 watch 导入
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/modules/user'
	import {
		useChatStore
	} from '@/stores/modules/chat'
	import {
		useDeviceStore
	} from '@/stores/modules/device'
	import {
		system
	} from '@/utils'

	const statusBarHeight = system.getStatusBarHeight()
	const userStore = useUserStore()
	const chatStore = useChatStore()
	const deviceStore = useDeviceStore()

	// 状态管理
	const userInfo = computed(() => userStore.userInfo)
	const messages = computed(() => chatStore.messages)
	const inputContent = ref('')
	const deviceInfo = ref(null)
	const lastMessageId = ref('')

	// 监听消息变化
	watch(messages, (newMessages) => {
		console.log('Messages updated:', newMessages)
		nextTick(() => {
			scrollToBottom()
		})
	}, {
		deep: true
	})

	// 发送消息
	const sendMessage = async () => {
		const content = inputContent.value?.trim()
		if (!content || chatStore.loading) return

		try {
			console.log('准备发送消息:', {
				content,
				deviceId: deviceInfo.value?.id,
				timestamp: Date.now()
			})

			const message = {
				message: content,
				sessionId: deviceInfo.value?.id?.toString()
			}

			// 清空输入框
			inputContent.value = ''

			// 发送消息并等待响应
			await chatStore.sendMessage(message)

			console.log('消息发送成功')

		} catch (error) {
			console.error('发送失败:', error)
			uni.showToast({
				title: '发送失败',
				icon: 'none'
			})
		}
	}

	// 滚动到底部
	const scrollToBottom = () => {
		if (messages.value?.length) {
			lastMessageId.value = `msg-${messages.value[messages.value.length - 1].id}`
			console.log('Scrolling to message:', lastMessageId.value)
		}
	}

	// 初始化聊天
	onLoad((options) => {
		console.log('Chat page loaded with options:', options)
		initChat(parseInt(options.id))
	})

	// 初始化聊天 方法
	const initChat = async (deviceId) => {
		if (!deviceId) {
			uni.showToast({
				title: '无效的设备ID',
				icon: 'none'
			})
			return
		}

		try {
			console.log('Initializing chat with device ID:', deviceId)
			chatStore.setCurrentDeviceId(deviceId)

			const devices = await deviceStore.loadPrivateDevices()
			const device = devices.find(d => d.id === deviceId)

			if (!device) {
				throw new Error('设备不存在')
			}
			console.log('Found device:', device)
			deviceInfo.value = device

			// 如果没有历史消息，添加智能体的自我介绍
			if (!chatStore.messages.length) {
				// 直接添加一条AI的自我介绍消息
				const introMessage = {
					id: Date.now(),
					role: 'assistant', // 修改为 assistant 角色
					content: device.description,
					timestamp: Date.now()
				}
				chatStore.addMessage(introMessage)
			}

		} catch (error) {
			console.error('初始化失败:', error)
			uni.showToast({
				title: '初始化失败',
				icon: 'none'
			})
		}
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}

	// 加载更多历史记录
	const loadMoreHistory = async () => {
		if (chatStore.loading || !deviceInfo.value) return

		try {
			const page = Math.floor(messages.value.length / 20) + 1
			await chatStore.getMessages(deviceInfo.value.id, page, 20)
		} catch (error) {
			console.error('加载更多消息失败:', error)
		}
	}

	// 格式化时间
	const formatTime = (timestamp) => {
		if (!timestamp) return ''
		const date = new Date(timestamp)
		return date.toLocaleTimeString('zh-CN', {
			hour: '2-digit',
			minute: '2-digit'
		})
	}

	// 是否显示时间戳
	const shouldShowTimestamp = (currentMsg, prevMsg) => {
		if (!currentMsg?.timestamp || !prevMsg?.timestamp) return false
		return currentMsg.timestamp - prevMsg.timestamp > 5 * 60 * 1000
	}

	// 消息列表监听
	watch(() => messages.value, (newMessages) => {
		console.log('Messages updated:', newMessages);
	}, {
		deep: true
	});
</script>

<style lang="scss">
	.chat-container {
		min-height: 100vh;
		background: #f7f7f7;

		.nav-bar {
			height: 88rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			background: #fff;
			border-bottom: 1px solid #eee;

			.left {
				margin-right: 20rpx;

				.back-icon {
					font-size: 36rpx;
					color: #333;
				}
			}

			.title-container {
				flex: 1;

				.avatar-title {
					display: flex;
					align-items: center;

					.avatar {
						width: 72rpx;
						height: 72rpx;
						border-radius: 50%;
						margin-right: 16rpx;
					}

					.title-info {
						display: flex;
						flex-direction: column;
						justify-content: center;

						.name {
							font-size: 32rpx;
							font-weight: 500;
							color: #333;
							line-height: 1.2;
						}

						.creator {
							font-size: 24rpx;
							color: #999;
							line-height: 1.2;
						}
					}
				}
			}
		}

		.message-list {
			flex: 1;
			padding: 30rpx;
			padding-bottom: 120rpx;

			.message-item {
				display: flex;
				margin-bottom: 30rpx;

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					flex-shrink: 0;
				}

				.content {
					max-width: 60%; // 减小最大宽度
					padding: 20rpx 24rpx;
					border-radius: 12rpx;
					font-size: 28rpx;
					margin: 0 20rpx;
					word-break: break-all;
				}

				&.user {
					flex-direction: row-reverse;

					.content {
						margin-right: 40rpx; // 增加右侧边距
						background: #007AFF;
						color: #fff;
					}

					.avatar {
						margin-right: 50rpx; // 增加头像右侧边距
					}
				}

				&.assistant {
					.content {
						margin-left: 20rpx;
						background: #fff;
						color: #333;
					}
				}
			}
		}

		.input-box {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 20rpx;
			background: #f7f7f7;
			display: flex;
			align-items: center;
			border-top: 1px solid #eee;
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

			.input {
				flex: 1;
				height: 72rpx;
				background: #fff;
				border-radius: 36rpx;
				padding: 0 30rpx;
				font-size: 28rpx;
			}

			.send-btn {
				width: 120rpx;
				height: 72rpx;
				line-height: 72rpx;
				text-align: center;
				margin-left: 20rpx;
				border-radius: 36rpx;
				font-size: 28rpx;
				background: #f0f0f0;
				color: #999;

				&.active {
					background: #007AFF;
					color: #fff;
				}
			}
		}
	}
</style>